var fs = require("fs");
var path = require("path");
var prettier = require("prettier");

// 遍历搜索css变量
function getCssVariables(theme, father = "") {
  let variables = {};
  for (let key in theme) {
    if (typeof theme[key] === "object") {
      variables = Object.assign(variables, getCssVariables(theme[key], father + "-" + key));
    } else {
      variables[father + "-" + key] = theme[key];
    }
  }
  return variables;
}

// 设置css变量
function setCssVariables(theme) {
  let cssVariables = getCssVariables(theme);
  for (let key in cssVariables) {
    document.documentElement.style.setProperty("-" + key, cssVariables[key]);
  }
}

// 获取指定名称的cookie
function getCookie(name) {
  let strCookie = document.cookie;
  let arrCookie = strCookie.split("; ");
  for (let i = 0; i < arrCookie.length; i++) {
    let arr = arrCookie[i].split("=");
    if (arr[0] === name) {
      return arr[1];
    }
  }
  return "";
}

module.exports = function writeTheme(theme, category) {
  // 编译前配置
  let stylePath = path.normalize(".prettierrc");
  let themePath = path.normalize("./static/boxy/theme/theme.js");
  let style = JSON.parse(fs.readFileSync(stylePath, "utf8"));

  // js编译
  style["parser"] = "babel";
  let jsText = "boxyTheme = " + JSON.stringify(theme) + ";\n\n\n";
  jsText += String(getCssVariables) + "\n\n\n";
  jsText += String(setCssVariables) + "\n\n\n";
  jsText += String(getCookie) + "\n\n\n";
  jsText += 'setCssVariables(boxyTheme[getCookie("themeMode")||"light"]);';
  fs.writeFileSync(themePath, prettier.format(jsText, style), "utf8");
  console.log("The theme file is generated on " + themePath);

  //css编译
  style["parser"] = "css";
  let cssText = ":root {";
  let mode = Object.keys(theme)[0];
  let cssVariables = getCssVariables(theme[mode]);
  for (let key in cssVariables) {
    cssText += "-" + key + ": " + cssVariables[key] + ";";
  }
  cssText += "}";
  let cssPath = path.normalize("./static/boxy/theme/theme.default.css");
  fs.writeFileSync(cssPath, prettier.format(cssText, style), "utf8");
  console.log("The theme file is generated on " + cssPath );

  // category编译
  let categoryText = "";
  let categoryDef = getCssVariables(category);
  for (let key in categoryDef) {
    categoryText += "iconpark-icon[name='" + key.slice(1) + "']{background-color:" + categoryDef[key] + ";}";
  }
  categoryText += "iconpark-icon[name='testing'] {opacity: 50%;filter: blur(3px);}";
  let categoryPath = path.normalize("./static/boxy/toolbox/color.css");
  fs.writeFileSync(categoryPath, prettier.format(categoryText, style), "utf8");
  console.log("The theme file is generated on " + categoryPath + "\n");
};
